package io.ouka.jvm.hotspot.selfread.methodinvoke;

import com.sun.xml.internal.ws.api.server.SDDocument;
import io.ouka.jvm.hotspot.selfread.InstanceKlass;
import io.ouka.jvm.hotspot.selfread.domain.CodeAttribute;
import io.ouka.jvm.hotspot.selfread.domain.MethodInfo;

import java.util.Stack;

/**
 * @author ouka
 * JavaNativeInterface
 */
public class JavaNativeInterface {
    public static MethodInfo getMethodID(InstanceKlass instanceKlass, String className,String methodDescriptor){

        MethodInfo[] methods = instanceKlass.getMethods();

        for (MethodInfo method : methods) {
            int nameIndex = method.getNameIndex();//method name index
            String methodName = (String) instanceKlass.getConstantPool().getDataMap().get(nameIndex);
            int descriptorIndex = method.getDescriptorIndex(); //method descriptorIndex
            String methodDescriptorStr = (String) instanceKlass.getConstantPool().getDataMap().get(descriptorIndex);

            if (methodName.equalsIgnoreCase(className)&&methodDescriptorStr.equalsIgnoreCase(methodDescriptor)){
                System.out.println("方法：++"+methodName+"++  描述"+methodDescriptorStr);
                return method;
            }

        }

        System.err.println("没有找到该方法：++"+methods+"++  描述"+methodDescriptor);
        return null;
    }



    public static void callStaticMethod(MethodInfo methodInfo){
//          解析method  解析字节码
        /**
         * 1 获取当前线程
         * 2 获取当前线程的虚拟机栈
         * 3 解析当前方法（静态）
         * 4 创建栈帧
         * 5 读取字节码执行
         */
        JavaThread javaThread = Threads.currentThread();
        CodeAttribute[] codeAttributes = methodInfo.getCodeAttributes();
        JavaVFrame javaVFrame = new JavaVFrame(codeAttributes[1].getMaxLocals(),methodInfo);
        javaThread.getStack().push(javaVFrame);//往虚拟机栈里面压入栈帧
        BytecodeInterpreter.run(javaThread,methodInfo);


    }
}
